package com.stray.crawl.supt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

import com.stray.crawl.utils.DataUtils;
import com.stray.crawl.utils.IOUtils;

public class FileStorage {

	private File rootFile;

	public FileStorage(String rootPath) {
		rootFile = new File(rootPath);
	}

	public File getPersistDirectoryFile(String... groups) throws IOException {
		StringBuffer buf = new StringBuffer();

		buf.append("results").append(File.separator);
		for (String group : groups) {
			buf.append(group).append(File.separator);
		}

		File file = new File(rootFile, buf.toString());
		if (!file.exists()) {
			if (!file.mkdirs()) {
				throw new IOException(buf.toString() + " fail to create directory structure.");
			}
		} else if (!file.isDirectory()) {
			throw new IOException(buf.toString() + " not a directory.");
		}

		return file;
	}

	public String getResourcePath(String filename, String... groups) throws IOException {
		StringBuffer buf = new StringBuffer();

		buf.append("resources").append(File.separator);
		if (groups != null && groups.length > 0) {
			for (String group : groups) {
				if (!DataUtils.isEmpty(group)) {
					buf.append(group).append(File.separator);
				}
			}
		}
		buf.append(filename);

		File file = new File(rootFile, buf.toString());
		File parentFile = file.getParentFile();

		if (!parentFile.exists()) {
			if (!parentFile.mkdirs()) {
				throw new IOException(parentFile.getCanonicalPath() + " fail to create directory structure.");
			}
		} else if (!parentFile.isDirectory()) {
			throw new IOException(parentFile.getCanonicalPath() + " not a directory.");
		}


		return file.getCanonicalPath();
	}

	public void storeToPath(String filePath, InputStream in) throws IOException {
		OutputStream out = null;

		try {
			out = new FileOutputStream(new File(filePath));

			IOUtils.copyStream(in, out);
		} finally {
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(out);
		}
	}

	public void storeToPath(String filePath, Reader in, String charset) throws IOException {
		Writer out = null;

		try {
			out = new OutputStreamWriter(new FileOutputStream(new File(filePath)), charset);

			IOUtils.copyStream(in, out);
		} finally {
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(out);
		}
	}

}